package com.paradogs.framework.core.msg;

import com.baidu.bjf.remoting.protobuf.annotation.ProtobufClass;
import com.paradogs.framework.core.msg.PRMsg;
import io.netty.channel.Channel;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;


/**
 * @author: yumi
 * @date: 2023/8/15  15:28
 * @Description: TODO
 */
@Slf4j
@Data
@ProtobufClass
public class Connection {

    /**
     * 通道
     */
    private Channel channel;

    /**
     * 连接状态
     */
    private State state = State.WAIT_INIT;

    /**
     * 目标服务类型
     */
    private String targetServer;

    /**
     * 目标服务名称
     */
    private String targetName;


    public Connection(Channel channel) {
        this.channel = channel;
    }

    /**
     * 初始化连接服务器信息
     * @param targetServer
     * @param targetName
     */
    public void init(String targetServer, String targetName) {
        if (state != State.WAIT_INIT) {
            log.warn("masterClient already init: [server: {}, name: {}]", targetServer, targetName);
            return;
        }
        this.targetServer = targetServer;
        this.targetName = targetName;
        this.state = State.RUNNING;
        log.info("Init masterClient: {}", targetServer);
    }

    public String getHost() {
        return ((InetSocketAddress) this.channel.remoteAddress()).getHostString();
    }

    public int getPort() {
        return ((InetSocketAddress) this.channel.remoteAddress()).getPort();
    }


    public enum State {
        /**
         * 等待初始化数据
         */
        WAIT_INIT,
        /**
         * 正常运行中
         */
        RUNNING,
        /**
         * 停止
         */
        STOP
    }

}
